<?php

namespace app\backend\service;

use app\common\RootService;
use app\common\model\ConvertModel;
use app\backend\validate\ConvertValidate;

class ConvertService extends RootService
{
    /**
     * 提现标识
     * @return array
     */
    public function convertLabel()
    {
        $labelData = ['stateLabel' => ConvertModel::$stateLabel, 'currencyLabel' => ConvertModel::$currencyLabel,
            'typeLabel' => ConvertModel::$typeLabel, 'color' => ConvertModel::$color, 'auditLabel' => ConvertModel::$auditLabel];
        unset($labelData['currencyLabel'][0], $labelData['currencyLabel'][3]);
        return $labelData;
    }

    /**
     * 套餐列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function lists(array $params)
    {
        // 状态
        $convertLabel = $this->convertLabel();
        // 管理员名称
        $adminNames = AdminService::adminNames();
        // 数据源
        $convertList = $this->page($this->convertModel($params)->order(['sort' => 'asc']));
        // 数据处理
        array_walk($convertList['data'], function (&$row) use ($convertLabel, $adminNames) {
            empty($row['prompt']) && $row['prompt'] = '--';
            empty($row['remark']) && $row['remark'] = '--';
            $row['color'] = $convertLabel['color'][$row['state']];
            $row['typeLabel'] = $convertLabel['typeLabel'][$row['type']] ?? '--';
            $row['name'] = str_replace('%s', $row['quantity'], $row['name']);
            $row['auditLabel'] = $convertLabel['auditLabel'][$row['audit']] ?? '--';
            $row['stateLabel'] = $convertLabel['stateLabel'][$row['state']] ?? '--';
            $row['currencyLabel'] = $convertLabel['currencyLabel'][$row['currency']] ?? '--';
            $row['adminName'] = $adminNames[$row['admin_id']]['real_name'] ?? $adminNames[$row['admin_id']]['admin_name'];
        });
        return $convertList;
    }

    /**
     * 新增套餐
     * @param array $params
     * @return string[]
     * @throws \app\common\RootException
     */
    public function add(array $params)
    {
        // 参数校验
        $this->verify($params, 'add');
        // 提示信息
        $tipMsg = "【{$params['name']}】添加";
        // 添加失败
        ConvertModel::create($this->formData($params)) || $this->errorException("{$tipMsg}失败");
        // 添加成功
        return ['msg' => "{$tipMsg}成功", 'preload' => true];
    }


    /**
     * 编辑套餐
     * @param array $params
     * @return string[]
     * @throws \app\common\RootException
     */
    public function edit(array $params)
    {
        // 参数校验
        $this->verify($params, 'edit');
        // 提示信息
        $tipMsg = "【{$params['name']}】修改";
        // 修改失败
        ConvertModel::update($this->formData($params)) || $this->errorException("{$tipMsg}失败");
        // 修改成功
        return ['msg' => "{$tipMsg}成功", 'preload' => true];
    }

    /**
     * 套餐详情
     * @param int $convertId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $convertId)
    {
        return ConvertModel::where(['id' => $convertId])->find()->toArray();
    }

    /**
     * 删除套餐
     * @param int $convertId
     * @return array
     * @throws \app\common\RootException
     */
    public function del(int $convertId)
    {
        ConvertModel::where(['id' => $convertId])->delete() || $this->errorException('删除失败');
        return ['msg' => '删除成功', 'reload' => true];
    }

    /**
     * 表单数据
     * @param array $params
     * @return array
     */
    protected function formData(array $params)
    {
        // 数据处理
        $postData = ['remark' => $params['remark'], 'quantity' => $params['quantity'], 'currency' => $params['currency'],
            'type' => $params['type'], 'state' => $params['state'], 'name' => $params['name'], 'prompt' => $params['prompt'],
            'frequency' => $params['frequency'], 'audit' => $params['audit'], 'receipt' => $params['receipt']];
        // 排序（数字越小越靠前）
        is_numeric($params['sort']) && $postData['sort'] = $params['sort'];
        // 钻石数量
        is_numeric($params['diamond']) && $postData['diamond'] = $params['diamond'];
        // 添加Or编辑
        empty($params['id']) ? $postData['admin_id'] = adminInfo('id') : $postData['id'] = $params['id'];
        return $postData;
    }

    /**
     * 参数校验
     * @param array $params
     * @param string $scene
     * @throws \app\common\RootException
     */
    protected function verify(array $params, string $scene)
    {
        $validate = new ConvertValidate();
        // 参数校验
        $validate->scene($scene)->check($params) || $this->errorException($validate->getError());
        // 实收金额校验
        in_array($params['type'], [1]) || empty($params['receipt']) && $this->errorException('实收金额必须大于0');
    }

    /**
     * 转换套餐模型
     * @param array $params
     * @return ConvertModel
     */
    protected function convertModel(array $params)
    {
        // 套餐名称筛选
        empty($params['name']) || $where[] = ['name', 'like', $params['name'] . '%'];
        // 钱包类型筛选
        condition($params['type'] ?? '') && $where[] = ['type', 'in', explode(',', $params['type'])];
        // 套餐状态筛选
        condition($params['state'] ?? '') && $where[] = ['state', 'in', explode(',', $params['state'])];
        // 货币类型筛选
        condition($params['currency'] ?? '') && $where[] = ['currency', 'in', explode(',', $params['currency'])];
        // 筛选结果
        return ConvertModel::where($where ?? []);
    }
}